package com.bezdelnick.forum.dao.hibernate;

import com.bezdelnick.forum.dao.IRoleDao;
import com.bezdelnick.forum.domain.UserRole;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Property;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * Created by IntelliJ IDEA.
 * User: Bezdelnick
 * Date: 21.08.12
 * Time: 17:22
 * To change this template use File | Settings | File Templates.
 */
public class RoleDaoImpl implements IRoleDao {
    private static final Logger LOGGER = LoggerFactory.getLogger(AppUserDaoImpl.class);

    @Autowired(required = true)
    private SessionFactory sessionFactory;

    @Override
    public List<UserRole> loadRolesByUserId(long id) {
        List<UserRole> userRoles = null;
        Session session = null;
        try {
            session = sessionFactory.openSession();
            userRoles = session.createCriteria(UserRole.class).add(Property.forName("userId").eq(id)).list();
            return userRoles;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return null;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public boolean insertRolesByUserId(long id, String[] roles) {
        Session session = null;
        try {
            session = sessionFactory.openSession();

            for (String role : roles) {
                UserRole userRole = new UserRole();
                userRole.setUserId(id);
                userRole.setAuthority(role);
                session.save(userRole);
            }
            return true;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return false;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }

    @Override
    public boolean deleteRolesByUserId(long id) {
        Session session = null;
        try {
            session = sessionFactory.openSession();
            String hql ="delete from UserRole role where role.userId= :id";
            Query query = session.createQuery(hql);
            query.setLong("id", id);
            query.executeUpdate();
            return true;
        } catch (Error error) {
            LOGGER.error(error.getMessage());
            return false;
        } finally {
            if (session.isOpen())
                session.close();
        }
    }
}
